use crate::app::UIComponent;
use crate::data::{Node, NodeAttr};
use eframe::egui::{Align, Layout, SidePanel, TextBuffer, TextEdit, Ui, Vec2};

#[derive(Default)]
pub struct NodeAttribute {
    item_height: f32,
}

impl NodeAttribute {
    pub fn new() -> Self {
        Self::default()
    }

    fn attr_ui(&mut self, ui: &mut Ui) {
        ui.vertical_centered(|ui| {
            ui.heading("节点属性");
            // title : value
            let node = Node::get_current_node(ui.ctx());
            if let Ok(mut node) = node.try_lock() {
                self.attr_item_ui(
                    ui,
                    &mut node.title,
                );
                self.attr_item_ui(
                    ui,
                    &mut node.params,
                );
            };
        });
    }

    fn attr_item_ui<T: TextBuffer> (&mut self, ui: &mut Ui, attr: &mut NodeAttr<T>) {
        ui.allocate_ui_with_layout(
            Vec2::new(ui.available_width(), self.item_height),
            Layout::left_to_right(Align::Center),
            |ui| {
                let resp = ui.label(&attr.title).on_hover_text(&attr.tips);
                self.item_height = resp.rect.height();
                let title = TextEdit::singleline(&mut attr.value)
                    .desired_width(ui.available_width());
                ui.add(title);
            },
        );
    }
}

impl UIComponent for NodeAttribute {
    fn update(&mut self, ui: &mut Ui) {
        // 节点信息
        SidePanel::right(ui.next_auto_id())
            .resizable(true)
            .show_inside(ui, |ui| {
                self.attr_ui(ui);
            });
    }
}
